package com.tdk.wifidirectserver.ui.main

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.tdk.wifidirectserver.APConnectActivity
import com.tdk.wifidirectserver.MainActivity
import com.tdk.wifidirectserver.R
import com.tdk.wifidirectserver.databinding.FragmentConnectedClientBinding
import com.tdk.wifidirectserver.ui.chat.ChatFragment


class ConnectedClientFragment : Fragment() {
    private val TAG = "ConnectedClientFragment"
    private lateinit var binding: FragmentConnectedClientBinding
    private lateinit var viewModel: MainViewModel
    lateinit var connectedClientViewModel: ConnectedClientViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        connectedClientViewModel = ViewModelProvider(this)[ConnectedClientViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentConnectedClientBinding.inflate(layoutInflater, container, false)
        initView()
        return binding.root
    }

    private fun initView() {


        binding.identifyInfoTv.text = "GroupClient"

        viewModel.connectedWifiP2pInfo.observe(viewLifecycleOwner) {
            if (it.isNotBlank()) {
                binding.identifyInfoTv.text = "GroupClient:[GroupOwnerIP:${it}]"
            }
        }

        connectedClientViewModel.socketConnectStatus.observe(viewLifecycleOwner) {
            Log.d(TAG, "socketConnectStatus: $it")
            if (it) {
                binding.disconnectSocketBt.isEnabled = true
                binding.connectSocketBt.isEnabled = false
                activity?.supportFragmentManager?.beginTransaction()
                    ?.replace(
                        R.id.fragment_container,
                        ChatFragment.newInstance(false, "", connectedClientViewModel),
                        ChatFragment::class.java.simpleName
                    )
                    ?.commit()

            } else {
                binding.disconnectSocketBt.isEnabled = false
                binding.connectSocketBt.isEnabled = true
                val chatFragment =
                    activity?.supportFragmentManager?.findFragmentByTag(ChatFragment::class.java.simpleName)
                if (chatFragment != null) {
                    activity?.supportFragmentManager?.beginTransaction()?.remove(chatFragment)?.commit()
                }
            }


        }
        if (context is APConnectActivity) {
            binding.btDisconnect.visibility = View.GONE
        }
        binding.btDisconnect.setOnClickListener {
            viewModel.disconnect()
        }


        binding.connectSocketBt.setOnClickListener {
            if (viewModel.connectedWifiP2pInfo.value!!.isNotBlank()) {
                connectedClientViewModel.startClient(viewModel.connectedWifiP2pInfo.value!!, 8888)
            }
        }

        binding.disconnectSocketBt.setOnClickListener {
            connectedClientViewModel.closeClient()
        }


        binding.btStartDiscoveryNsd.setOnClickListener {
            connectedClientViewModel.startDiscoveryNSD()
        }

        binding.btStopDiscoveryNsd.setOnClickListener {
            connectedClientViewModel.stopDiscoveryNSD()
        }

        connectedClientViewModel.nsdServiceInfoLiveData.observe(viewLifecycleOwner) {
            if (it != null) {
                var port = it.port
                var host = if (Build.VERSION.SDK_INT >= 34) {
                    it.hostAddresses[0].hostAddress
                } else {
                    it.host.hostAddress
                }
                val name = it.serviceName
                Log.d(TAG, "nsdServiceInfoLiveData: $host:$port $name")
            } else {
                Log.d(TAG, "nsdServiceInfoLiveData: null")
            }
        }

    }

    companion object {
        @JvmStatic
        fun newInstance() =
            ConnectedClientFragment()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MainActivity) {
            viewModel = context.viewModel
        }

    }
}